
#include <iostream>
#include "Intaddr.h"
#include "Log.h"
#include "Common.h"
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "使用方式错误,正确调用方式 ./serve ip port" << std::endl;
        exit(Err_Use);
    }
    zmh::Intaddr serve_addr(AF_INET, argv[1], std::stoi(argv[2]));
    // 打开网卡
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        LOG(zmh::FATAL) << "socket mistake";
        exit(Err_Socket);
    }
    LOG(zmh::INFO) << "socket sucess";
    // 请求连接
    if ((connect(fd, (const sockaddr *)&serve_addr.Addr(), sizeof(serve_addr.Addr()))) == -1)
    {
        LOG(zmh::FATAL) << "connect mistake";
        exit(Err_Connect);
    }
    LOG(zmh::INFO) << "connect sucess";
    while (true)
    {
        // 发送消息 --- 你要远程服务器执行的指令
        std::string mes;
        std::cout << "Please Input:";
        std::getline(std::cin, mes);
        if(mes.size() == 0) continue;
        int n = write(fd, mes.c_str(), mes.size());
        // 接受消息 --- 服务器执行指令的运行结果
        char buffer[1024];
        n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}